import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Form, Input } from "antd";
import OpenApi from '../../utils/api.jsx'; // 导入API函数
import "./login.css";

const Login = (props) => {
  const mobile = useRef("");
  const password = useRef("");
  const captcha = useRef("");
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [base, setBase] = useState({});
  const [formButtonLoading, setFormButtonLoading] = useState(false);

  const fetchCaptcha = async () => {
    try {
      const res = await OpenApi.getCaptcha();
      setBase(res.data);
    } catch (error) {
      console.error('Error fetching captcha:', error);
    }
  };

  const onFinish = (values) => {
    console.log('Received values of form: ', values);
  };

  const handleLogin = async () => {
    setFormButtonLoading(true);
    try {
      const values = form.getFieldsValue();
      const { data } = await OpenApi.passwordLogin(values.mobile, values.password, values.captcha, base.captchaid);
      setFormButtonLoading(false);
      if (data.code === 200) {
        alert("登录成功");
        localStorage.setItem("token", data.x_token);
        localStorage.setItem("id", data.id);
        localStorage.setItem("role", data.role);
        localStorage.setItem("username", data.username);
        localStorage.setItem("name", data.name);

        if (data.role === 2 || data.role === 3) {
          navigate("/home");
        } else if (data.role === 1) {
          navigate("/user");
        }
      } else {
        alert("账号或密码输入错误，请重新输入");
      }
    } catch (error) {
      setFormButtonLoading(false);
      console.error('Error:', error);
    }
  };

  const redirectToRegister = () => {
    navigate("/register");
  };

  const redirectToFindPassword = () => {
    navigate("/findPassword");
  };

  return (
    <div className="container">
      <div className="login-wrapper">
        <div className="header">欢 迎 登 录</div>
        <Form onFinish={onFinish} form={form}>
          <div className="form-wrapper">
            <Form.Item
              label="手机号"
              name="mobile"
              ref={mobile}
              rules={[
                {
                  required: true,
                  message: "手机号不能为空",
                }, {
                  pattern: /^\d{11}$/,
                  message: "请输入正确的手机号",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              ref={password}
              rules={[
                {
                  required: true,
                  message: "密码不能为空",
                },
                {
                  validator: (_, value) =>
                    value && !/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/.test(value)
                      ? Promise.reject(
                          new Error('密码长度必须在6到10个字符之间,并且包含至少一个字母和一个数字')
                        )
                      : Promise.resolve()                  
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="验证码"
              name="captcha"
              ref={captcha}
              rules={[
                {
                  required: true,
                  message: "验证码不能为空",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <img src={`${base.picCode}`} onClick={fetchCaptcha} alt="captcha" />
            <div className="btn">
              <Button type="primary" htmlType="submit" onClick={handleLogin} loading={formButtonLoading}>登录</Button>
            </div>
          </div>
        </Form>

        <div className="msg">
          没有账户?
          <a onClick={redirectToRegister}>点 击 注 册</a>
        </div>
        <div className="msg">
          忘记密码?
          <a onClick={redirectToFindPassword}>找 回 密 码</a>
        </div>
      </div>
    </div>
  );
};

export default Login;
